package com.effectiv.gooruda.rest.api.service;

import java.util.List;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.effectiv.gooruda.rest.api.domain.Email;
import jodd.mail.EmailAttachment;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;
import jodd.mail.att.InputStreamAttachment;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class EmailHandlerTemplate {
	
	@Async
	public void send(Email email, SmtpServer server, List<MultipartFile> attachments, List<MultipartFile> inlines){
		jodd.mail.Email e = jodd.mail.Email.create();
		//From
		e.from(email.getFrom());
		//TO
		e.setTo(email.getTo());
		//CC
		if(email.getCc() != null){
			e.setCc(email.getCc());
		}
		
		//BCC
		if(email.getBcc() != null) {
			e.setBcc(email.getBcc());
		}
		
		//Subject
		e.setSubject(email.getSubject());
		
		
		//TODO - if template present all others are ignored.
		//TODO - next release
		
		
		e.addText(email.getText());
		e.addHtml(email.getHtml(), "UTF-8");
		
		String replyTo [] = null;
		
		if(StringUtil.isBlank(email.getReplyTo())){
		
			replyTo = new String[] {email.getFrom(), "info@gooruda.com"};
		}
		else{
			replyTo = new String[] {email.getFrom(), "info@gooruda.com", email.getReplyTo()};
		}
		
		e.setReplyTo(replyTo);
		
		//TODO later release
		//e.setPriority(CommonEmail.PRIORITY_HIGH);

		for(MultipartFile f : attachments){
			if(!f.isEmpty())
			try{
				EmailAttachment emailAttachment = new InputStreamAttachment(f.getInputStream(),f.getContentType(), f.getOriginalFilename(), "x");
				e.attach(emailAttachment);
			}
			catch(Exception ex){
				log.error("Error with attachment", ex);
			}
		}
		
		SendMailSession session = server.createSession();
		session.open();
		session.sendMail(e);
		session.close();
	}
}
